package com.dddd.blog.blogcommon.utils;


import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Jwt工具类
 * @author 喵星球的大橘
 */

@Data
@Component
public class JwtUtils {

    private static final String SECRET = "Jwt Token Secret";

    /**
     * 创建Token
     * @param userName
     * @param  expireMills
     * @return
     */
    public static String createToken(String userName, long expireMills){
        SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;

        long nowMills = System.currentTimeMillis();

        Date now = new Date(nowMills);

        //创建payload
        Map<String, Object> claims = new HashMap();
        claims.put("username", userName);


        JwtBuilder builder = Jwts.builder()
                .setClaims(claims)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(now)
                .setSubject(userName)
                .signWith(algorithm,SECRET);

        Date date = new Date(nowMills + expireMills);

        builder.setExpiration(date);

        return builder.compact();
    }

    /**
     * 解析Token
     * @param token
     * @return
     */
    public static Claims parseToken(String token){
        JwtParser parser = Jwts.parser();
        Claims claims;

        try{
            claims = parser.setSigningKey(SECRET)
                    .parseClaimsJws(token).getBody();
        }catch(ExpiredJwtException e){
            claims = e.getClaims();
        }
        return claims;
    }


    /**
     * @param token
     * @return
     */
    public static boolean isExpired(String token){

        Claims claims = parseToken(token);
        Date expiration = claims.getExpiration();

        if(new Date(System.currentTimeMillis()).after(expiration)){
            System.out.println("过期了");
            return true;
        }
        return false;
    }

    /**
     * 获取剩余时间
     * @param token
     * @return
     */
    public static long getRemainTime(String token){
        Claims claims = parseToken(token);
        long last = claims.getExpiration().getTime() - System.currentTimeMillis();
        return last;
    }


    /**
     * 刷新获取新token
     * @return
     */
    public static String refreshToken(){
        return null;
    }


    public static void main(String[] args) {

        String token = createToken("dddd", 10 * 1000);

        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(isExpired(token));
    }
}
